using System;
using System.Collections.Generic;
using System.Text;
using JTest.DAO;
using JTest.DTO;

namespace JTest.BUS
{
    public class TestBUS
    {

        /// <summary>
        /// Return a TestDTO object
        /// </summary>
        /// <param name="numberofquestion">The number of question .</param>
        /// <param name="time">The test time.</param>
        /// <param name="type">The test type.</param>
        /// <param name="level">The test level.</param>
        /// <returns></returns>
        public static TestDTO test(int numberofquestion, long time, string type, int level)
        {
            TestDTO _testdto;

            // Call QuestionDAO to get list question for the test
            List<QuestionDTO> questions = QuestionDAO.getTestQuestionList(numberofquestion, type, level);

            // if question less than number of question required.
            if (questions.Count < numberofquestion)
            {
                _testdto = new TestDTO(questions, type, level, time);
            }
            else
            {
                // Create test dto object with random question
                List<QuestionDTO> testQuestions = new List<QuestionDTO>();
                Dictionary<int, int> randoms = new Dictionary<int, int>();

                while (randoms.Count != numberofquestion)
                {
                    //generate new random between one and total list count
                    int randomInt = new Random().Next(questions.Count);

                    // store this in dictionary to ensure uniqueness
                    try
                    {
                        randoms.Add(randomInt, randomInt);
                    }
                    catch (ArgumentException aex)
                    {
                        Console.Write(aex.Message);
                    } //we can assume this element exists in the dictonary already 

                    //check for randoms length and then iterate through the original list 
                    //adding items we select via random to the return list
                    if (randoms.Count == numberofquestion)
                    {
                        foreach (int key in randoms.Keys)
                            testQuestions.Add(questions[randoms[key]]);

                        break; //break out of _while_ loop
                    }
                }
                // Init a new TestDTO object with the question list
                _testdto = new TestDTO(testQuestions, type, level, time);
            }

            return _testdto;
        }
    }
}
